// pages/category/index.js
/*
import {request} from "../../request/index.js";
import regeneratorRuntime from '../../lib/runtime/runtime.js';
*/
// 获取应用实例
const app = getApp()
const db = wx.cloud.database()
Page({
  data: {
    // 左侧菜单数据
    leftMenuList: [
      "配菜类",
      "大米类",
      "干货类"
    ],
    rightContent: [],
    // 被点击的左侧的菜单
    currentIndex: 0,
    // 右侧内容的滚动条距离顶部的距离
    scrollTop: 0,
  },
  onLoad: function () {
    // 判断本地缓存是否还存在，若存在，就使用本地缓存的数据，如果没有就从服务器获取最上页的内容显示
    const sort0 = wx.getStorageSync('sort0');
    if (sort0) {
      this.setData({
        rightContent: sort0
      })
    } else {
      db.collection('sorts').where({
          index: 's0'
        })
        .get().then(res => {
          this.setData({
            rightContent: res.data
          })
        })
    }
  },
  //左侧菜单的点击事件
  handleItemTap(e) {
    const {
      index
    } = e.currentTarget.dataset;
    switch (index) {
      case 1: {
        const sort1 = wx.getStorageSync('sort1');
        if (sort1) {
          this.setData({
            rightContent: sort1
          })
        } else {
          let p1 = new Promise((resolve, reject) => {
            db.collection('sorts').where({
              index: 's1'
            }).get().then(res => {
              resolve(res.data);
            })
          })
          Promise.all([p1]).then((result) => {
            wx.setStorageSync('sort1', result[0]);
            this.setData({
              rightContent: result[0]
            })
          })
        }
        break;
      }
      case 0: {
        const sort0 = wx.getStorageSync('sort0');
        if (sort0) {
          this.setData({
            rightContent: sort0
          })
        } else {
          let p1 = new Promise((resolve, reject) => {
            db.collection('sorts').where({
              index: 's0'
            }).get().then(res => {
              resolve(res.data);
            })
          })
          Promise.all([p1]).then((result) => {
            wx.setStorageSync('sort0', result[0]);
            this.setData({
              rightContent: result[0]
            })
          })
        }
        break;
      }
      case 2: {
        const sort2 = wx.getStorageSync('sort2');
        if (sort2) {
          this.setData({
            rightContent: sort2
          })
        } else {
          let p1 = new Promise((resolve, reject) => {
            db.collection('sorts').where({
              index: 's2'
            }).get().then(res => {
              resolve(res.data)
            })
          })
          Promise.all([p1]).then((result) => {
            wx.setStorageSync('sort2', result[0]);
            this.setData({
              rightContent: result[0]
            })
          })
        }
        break;
      }
    }
  }
})